using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data.Contexts;
using UniversalAdmin.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace UniversalAdmin.Infrastructure.Repositories
{
  /// <summary>
  /// Entity Framework实现的通用仓储
  /// </summary>
  /// <typeparam name="T"></typeparam>
  public class EfRepository<T> : IRepository<T> where T : EntityBase
  {
    private readonly AdminDbContext _db;
    private readonly DbSet<T> _tb;

    public EfRepository(AdminDbContext db)
    {
      _db = db;
      _tb = db.Set<T>();
    }

    public IQueryable<T> Table {get { return _tb.AsNoTracking().Where(x => x.IsDelete == false); } }
    public IQueryable<T> All => _tb.AsNoTracking();

    public async Task<T> CreatedAsync(T entity)
    {
    var obj=    await _tb.AddAsync(entity);
      await _db.SaveChangesAsync();
      return obj.Entity;
    }



    public async Task DeleteAsync(Guid id)
    {
      var entity = await _tb.FindAsync(id);
      if (entity != null)
      {
        _tb.Remove(entity);
        await _db.SaveChangesAsync();
      }
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
      var list = await _tb.AsNoTracking().ToListAsync();
      return list;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
      return await _tb.FindAsync(id);
    }

    public async Task<T> UpdateAsync(T entity)
    {
      _tb.Update(entity);
      await _db.SaveChangesAsync();
      return entity;
    }

    public void AttachEntity(T entity)
    {
      _db.Attach(entity);
    }
  }
}